[Rails3] How to do multiple many to many relationships between the same two tables.

Posted by Kurt on Stack Overflow See other posts from Stack Overflow or by Kurt
Published on 2010-06-01T14:00:49Z Indexed on 2010/06/01 14:03 UTC
Read the original article Hit count: 183

Hi.

I have a model of a club where I want to model the two entities Meeting and Member.

There are actually two many-to-many relationships between these entities though, as for any meeting a Member can either be a Speaker or a Guest. Now I am an OO thinker, so would normally just create the two classes and each one would just have two arrays of the other inside, but rails is making me think a bit more data centric here, so I realise I need to break these M2M relationships up with join tables Speakers and Guests which I have done, but now I am having trouble describing the relationships in the models.

The two join table models both have "belongs_to :meeting" and "belongs_to :member" and I think that should be sufficient.

I am not however sure about the Meeting and Member models though.

Each one has "has_many :guests" and "has_many: speakers" but I am not sure if I also want to go: has_many :members, :through => :guests has_many :members, :through => :speakers

But I suspect that this is like declaring two "members" that will clash.

I also thought about: has_many :guests, :through => :guests has_many :speakers, :through => :speakers

Does that make sense? How would ActiveRecord know that they are in fact Members?

I have found heaps of examples of polymorphic m2m relationships and m2m relationships where 1 table references itself, but no good examples to help me mode this situation where two separate tables have two different m2m relationships.

Anyone got any tips?

© Stack Overflow or respective owner

Related posts about activerecord

Related posts about many-to-many